<?php

namespace app\index\controller\wanlshop;

use app\admin\model\User;
use app\api\controller\wanlshop\Separate;
use app\api\model\wanlshop\Industry;
use app\common\controller\Wanlshop;

use app\admin\library\traits\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 *
 *
 * @icon fa fa-circle-o
 */
class AddressSpot extends Wanlshop
{
    protected $noNeedLogin = '';
    protected $noNeedRight = '*';
//    use Backend;
    /**
     * AddressSpot模型对象
     * @var \app\admin\model\wanlshop\AddressSpot
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wanlshop\AddressSpot;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("statusWithdrawList", $this->model->getstatusWithdrawList());
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询

        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where('shop_id',$this->shop->id)
                    ->where('type',1)
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

//            foreach ($list as $row) {
//                $row->visible(['id','name','img','contacts','phone','address','time','createtime','status']);
//            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function multi($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->shop->id ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }

    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $this->view->assign('id', $ids);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $result = false;
        Db::startTrans();
        try {
            if(!isset($params['license_period_end'])){
                $params['license_period_end'] = '长期';
            }
            if(!isset($params['contact_period_end'])){
                $params['contact_period_end'] = '长期';
            }
            if(!isset($params['certificate_period_end'])){
                $params['certificate_period_end'] = '长期';
            }
            $user = User::where('mobile',$params['phone'])->find();
            if($user){
                $params['user_id'] = $user['id'];
            }else{
                $this->error(__('未找到此用户,请先去注册'));
            }
            $result = $this->model->where('id',$ids)->update($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function add()
    {
        if (false === $this->request->isPost()) {
            $industries = Industry::where('is_del',0)->where('level',2)->select();
            $this->view->assign('industries', $industries);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $result = false;
        Db::startTrans();
        try {
            $params['status'] = 2;
            $params['type'] = 1;
            $params['shop_id'] = $this->shop->id;
            $params['contact_type'] = 'LEGAL';
            $params['createtime'] = time();
            $params['shopname'] = $params['merchant_name'];
            $params['contact_id_doc_type'] = 'IDENTIFICATION_TYPE_IDCARD';
            if(!isset($params['license_period_end'])){
                $params['license_period_end'] = '长期';
            }
            if(!isset($params['contact_period_end'])){
                $params['contact_period_end'] = '长期';
            }
            if(!isset($params['certificate_period_end'])){
                $params['certificate_period_end'] = '长期';
            }
            $user = User::where('mobile',$params['phone'])->find();
            if($user){
                $params['user_id'] = $user['id'];
            }else{
                $this->error(__('未找到此用户,请先去注册'));
            }
            if($params['spot_type'] == 1){
                $params['status'] = 1;
            }
            $result = $this->model->allowField(true)->insertGetId($params);
            if($params['spot_type'] == 0){
                if($result){
                    //查看数据库中是否有一样的公司直接使用mch_id
                    $spot = $this->model->where('merchant_name',$params['merchant_name'])->order('id',"ASC")->find();
                    if($spot->sub_mchid){
                        $this->model->where('id',$result)->update([
                            'sub_mchid'=>$spot->sub_mchid
                        ]);
                    }else{
                        //提交微信商户申请单
                        $sep = new Separate();
                        $sep->application($result,false);
                    }
                }
            }

            Db::commit();

        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }


        $this->success();
    }
    public function endpoint()
    {
        $shop_id = $this->request->post('shop_id');
        $row = $this->model->get($shop_id);
        $separte = new Separate();
        $res = $separte->QueryApply($row['applyment_id']);
        if(isset($res['sub_mchid'])){
            $this->model->where('id',$shop_id)->update([
                'sub_mchid'=>$res['sub_mchid']
            ]);
        }
        switch ($res['applyment_state']){
            case 'APPLYMENT_STATE_EDITTING':
                $text = '编辑中,提交申请发生错误导致，请尝试重新提交';
                $status = 3;
                break;
            case 'APPLYMENT_STATE_AUDITING':
                $text = '审核中';
                $status = 2;
                break;
            case 'APPLYMENT_STATE_REJECTED':
                $text = '已驳回';
                $status = 3;
                break;
            case 'APPLYMENT_STATE_TO_BE_CONFIRMED':
                $text = '待账户验证';
                $status = 2;
                break;
            case 'APPLYMENT_STATE_TO_BE_SIGNED':
                $text = '待签约';
                $status = 4;
                break;
            case 'APPLYMENT_STATE_SIGNING':
                $text = '开通权限中';
                $status = 1;
                break;
            case 'APPLYMENT_STATE_FINISHED':
                $text = '已完成';
                $status = 1;
                break;
        }
        $this->model->where('id',$shop_id)->update([
                'status'=>$status
        ]);

        $this->success($text);
    }
    public function application()
    {
        $shop_id = $this->request->post('shop_id');
        $separte = new Separate();
        $separte->application($shop_id,false);
        $this->success();
    }

    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
    public function recyclebin()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->onlyTrashed()
            ->where('type',1)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }
    public function restore($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                $count += $item->restore();
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }
    public function destroy($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post('ids');
        $pk = $this->model->getPk();
        if ($ids) {
            $this->model->where($pk, 'in', $ids);
        }
        $count = 0;
        Db::startTrans();
        try {
            $list = $this->model->onlyTrashed()->select();
            foreach ($list as $item) {
                $count += $item->delete(true);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }


    public function withdraw()
    {
        //当前是否为关联查询

        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where('shop_id',$this->shop->id)
                ->where('type',2)   //2为核销点
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->visible(['id','name','img','contacts','phone','address','start_time','end_time','createtime','status']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function edit_withdraw($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            $this->view->assign('id', $ids);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->where('id',$ids)->update($params);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    public function add_withdraw()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        $result = false;
        Db::startTrans();
        try {
            $params['type'] = 2;
            $params['status'] = 1;
            $params['shop_id'] = $this->shop->id;
            $result = $this->model->allowField(true)->save($params);
            Db::commit();

        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }


        $this->success();
    }
    public function recyclebin_withdraw()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->onlyTrashed()
            ->where('type',2)
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }

    //平台自提点
    public function platformSpot()
    {
        $keywords = $this->request->post('name');
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $query = $this->model
            ->where('shop_id',0)
            ->whereIn('status',[1,4])
            ->where('type',1);   //2为核销点 1自提点
        if (!empty($keywords)) {
            $query->whereLike('name', "%$keywords%");
        }
        $keyValue = $this->request->post('keyValue','');

        if ($keyValue !== '') {
            $where = ['id' => ['in', $keyValue]];
            $query->where($where);
        }
        $list = $query->paginate(['page' => $page, 'list_rows' => $limit])->toArray();
        $result = [
            'code' => 0,
            'msg' => '获取成功',
            'total' => $list['total'],
            'list' => $list['data']
        ];

        return json($result);
    }
    //商家自提点
    public function shopSpot()
    {
        $keywords = $this->request->post('name');
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);


        $query = $this->model
            ->where('shop_id',$this->shop->id)
            ->whereIn('status',[1,4])
            ->where('type',1);   //2为核销点 1自提点
        if (!empty($keywords)) {
            $query->whereLike('name', "%$keywords%");
        }
        $keyValue = $this->request->post('keyValue','');

        if ($keyValue !== '') {
            $where = ['id' => ['in', $keyValue]];
            $query->where($where);
        }
        $list = $query->paginate(['page' => $page, 'list_rows' => $limit])->toArray();
        $result = [
            'code' => 0,
            'msg' => '获取成功',
            'total' => $list['total'],
            'list' => $list['data']
        ];

        return json($result);
    }
    //商家核销点
    public function shopWriteSpot()
    {
        $keywords = $this->request->post('name');
        $page = $this->request->get('page', 1);
        $limit = $this->request->get('limit', 10);
        $query = $this->model
            ->where('shop_id',$this->shop->id)
            ->whereIn('status',[1,4])
            ->where('type',2);   //2为核销点 1自提点
        if (!empty($keywords)) {
            $query->whereLike('name', "%$keywords%");
        }
        $keyValue = $this->request->post('keyValue','');

        if ($keyValue !== '') {
            $where = ['id' => ['in', $keyValue]];
            $query->where($where);
        }
        $list = $query->paginate(['page' => $page, 'list_rows' => $limit])->toArray();
        $result = [
            'code' => 0,
            'msg' => '获取成功',
            'total' => $list['total'],
            'list' => $list['data']
        ];

        return json($result);
    }
}
